import {ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ActionSheetController, AlertController, LoadingController, ModalController} from "@ionic/angular";
import {NativeService, spinnerList} from "../../services/native.service";
import {PreviewPictureComponent} from "../preview-picture/preview-picture.component";
import {DomSanitizer} from "@angular/platform-browser";
import {Files} from "../../../models/files";
import {WebView} from "@ionic-native/ionic-webview/ngx";
import {QiniuService} from "../../services/qiniu.service";
declare var MediaPicker: any;
import {File} from '@ionic-native/file/ngx';
import { Camera } from '@ionic-native/camera/ngx';
import {HttpService} from "../../services/http/http.service";
import {API} from "../../services/API";
import {UUID} from "angular2-uuid";
import {StorageService} from "../../services/storage.service";
import {StorageKey} from "../../Constants";
import {UserInfo} from "../../../models/UserInfo";
@Component({
  selector: 'app-upload-picture',
  templateUrl: './upload-picture.component.html',
  styleUrls: ['./upload-picture.component.scss'],
})
export class UploadPictureComponent implements OnInit {

  @Input() max = 9;  // 最多可选择多少张图片，默认为9张

  @Input() destinationType = 1;  // 期望返回的图片格式，默认1图片路径，0为返回图片base64

  @Input() allowAdd = true;  // 是否允许新增

  @Input() allowDelete = true;  // 是否允许删除

  @Input() fileObjList;  // 图片列表，与fileObjListChange形成双向数据绑定
  @Output() fileObjListChange = new EventEmitter<any>();
  @Input() category1 = '';
  @Input() pictureUrl = '';
  @Input () category2 = '';
  @Input() category3 = '';
  @Input() summaryId = '';
  @Input() applyId = '';
  @Input() option = '';
  @Output() optionChange = new EventEmitter<any>();
  mediaType: string;
  imgHeight: number;
  img = [];
  path: string;
  paths = [];
  // 图片格式和视频格式
  imgReg = /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/;
  @Input() uuid;
  imgIds;
  primaryNo;
  @Output() getUuid = new EventEmitter<any>();
  @Input() id;
  @Input() showFlag;
  @Output() showFlagChange = new EventEmitter<any>();
  uploadUser;
  constructor(public modalCtrl: ModalController,
              private actionSheetCtrl: ActionSheetController,
              private alertCtrl: AlertController,
              private nativeService: NativeService,
              public cd: ChangeDetectorRef,
              private sanitizer: DomSanitizer,
              private webview: WebView,
              private camera: Camera,
              private qiniuService: QiniuService,
              private file: File,
              private httpService: HttpService,
              private storage: StorageService,
              private loadingController: LoadingController
  ) {
    this.imgHeight = 10;
  }

  async ngOnInit() {
    console.log(75, this.fileObjList);
    let userInfo: UserInfo = await this.storage.read(StorageKey.PERSON_INFO);
    userInfo = userInfo? userInfo: {};
    this.uploadUser = userInfo.userId;
  }

  async addPicture() {
    // 如果不允许添加，跳出方法
    if(this.allowAdd == false){
      return;
    }
    if (!this.id) {
      this.uuid = UUID.UUID().replace(/-/g, '').toLocaleUpperCase();
      console.log(this.uuid);
      this.id = this.uuid;
      this.getUuid.emit(this.id);
    } else {
      this.uuid = this.id;
      console.log(this.uuid);
    }
    const actionSheet = await this.actionSheetCtrl.create({
      buttons: [
        {
          text: '从相册选择图片',
          icon: 'images',
          handler: () => {
            this.actionSheetCtrl.dismiss().then(() => {
              this.choosePic();
            }, () => {
              this.choosePic();
            });
          }
        },
        {
          text: '拍照',
          icon: 'camera',
          handler: () => {
            this.actionSheetCtrl.dismiss().then(() => {
              this.takePic();
            }, () => {
              this.takePic();
            });
          }
        },
        {
          text: '取消',
          cssClass: 'quxiao',
        }
      ]
    });
    return await actionSheet.present();
  }

  async deletePicture() { // 删除照片
    if ((!this.imgIds || this.imgIds == undefined) && this.fileObjList && this.fileObjList != undefined) {
      this.imgIds = this.fileObjList.id;
    }
    console.log(this.imgIds);
    return await this.nativeService.showConfirm('确认删除吗？', '确定', async () => {
      // @ts-ignore
      if (this.imgIds){
        const param = {
          summaryId: this.summaryId,
          applyId: this.applyId,
          imgIds: [this.imgIds],
        };
        console.log(param);
        const info = await this.httpService.post(API.APPLY_IMAGE_DELETE, param, false);
        console.log('157'+info);
        if (info) {
          this.fileObjList = '';
          this.fileObjListChange.emit(this.fileObjList);
        }
        this.checkAllowAdd();
        this.cd.detectChanges();
      } else {
        this.fileObjList = '';
      }

    }, '取消');
  }

  async viewerPicture(item, event) {
    event.stopPropagation(); // 终止事件冒泡
    const photos = [];
    console.log(event);
    console.log(item);
    photos.push(item.thumbPath);
    console.log(photos);
    const modal = await this.modalCtrl.create({
      component: PreviewPictureComponent,
      componentProps: {
        images: photos,
        initialIndex: 1
      },
    });
    await modal.present();
  }

  private readBuffer(fileUrl, mime) {
    this.mediaType = mime;
    if (this.imgReg.test(fileUrl)) {
      // 解析本地文件系统URL
      this.file.resolveLocalFilesystemUrl(fileUrl)
          .then((entry) => {
            console.log('Entry: ' + JSON.stringify(entry));
            this.cd.detectChanges();
            // 查找包含该条目的父DirectoryEntry。如果此条目是其文件系统的根，则其父是它本身。
            entry.getParent((directoryEntry) => {
              console.log('Directory entry: ' + JSON.stringify(directoryEntry));
              // 开始读取文件
              const data = this.file.readAsArrayBuffer(directoryEntry.nativeURL, entry.name);
              console.log('data' + JSON.stringify(data));
              this.file.readAsArrayBuffer(directoryEntry.nativeURL, entry.name)
                  .then(async (imageData: ArrayBuffer) => {
                    // 获取文件后缀和当前时间戳
                    const ind = entry.name.lastIndexOf('.');
                    const fileType = entry.name.substr(ind + 1);
                    const time = new Date().getTime();
                    let blobData: any = {};
                    blobData = new Blob([imageData]);
                    blobData.lastModifiedDate = new Date();
                    blobData.name = `${time}.${fileType}`;
                    let fileObj = {
                      file: blobData,
                      origPath: entry.nativeURL,
                      thumbPath: this.sanitizer.bypassSecurityTrustUrl(
                          this.webview.convertFileSrc(entry.nativeURL)),
                      type: mime,
                      name: blobData.name,
                      origName: entry.name,
                    } as Files;
                    const data = await this.qiniuService.upload(fileObj.file);
                    const param = {
                      category1: this.category1,
                      category2: this.category2,
                      category3: this.category3,
                      summaryId: this.summaryId,
                      applyId: this.applyId,
                      // @ts-ignore
                      fileName: data.key,
                      filePath: 'http://loan.i2soft.net',
                      primaryNo: this.uuid,
                      uploadUser: this.uploadUser,
                    };
                    const info = await this.httpService.post(API.APPLY_IMAGE_UPLOAD, param, false);
                    if (info){
                      this.fileObjList = fileObj;
                      this.fileObjList.thumbPath = info.filePath + '/' + info.fileName;
                    }
                    this.imgIds = info.id;
                    this.primaryNo = info.primaryNo;
                    this.fileObjListChange.emit(this.fileObjList);
                    this.optionChange.emit(this.option);
                    this.getUuid.emit(this.primaryNo);
                    this.showFlagChange.emit(this.showFlag);
                    this.cd.detectChanges();
                  });
            }, (error) => {
              console.log('Can not resolve file directory: ' + JSON.stringify(error));
            });
          })
          .catch((error) => {
            console.log('Can not resolve file path: ' + JSON.stringify(error));
          });
    } else {
      this.nativeService.showToast({duration: 2000, message: '暂不支持该格式上传'});
    }
    console.log('265'+this.fileObjList);
  }

  private takePic() {
    const cameraOptions = {quality: 100, mediaType: 0};
    MediaPicker.takePhoto((media) => {
      media.quality = 80;
      MediaPicker.compressImage(media, (compressData) => {
        console.log('拍照的图片的path----' + compressData.uri);
        this.readBuffer(compressData.uri, media.mediaType);
      }, e => {
        console.log('Can not compressImage: ' + JSON.stringify(e));
      });
    }, (e) => {
      console.log('Can not takePhoto: ' + JSON.stringify(e));
    }, cameraOptions);
  }
  private choosePic() {
    const mode = 100;
    const options = {
      selectMode: mode,
      maxSelectCount: 1,
      maxSelectSize: 200000000,
    };
    MediaPicker.getMedias(options, async (medias) => {
      if (medias.length > 0) {
        for (let i = 0; i < medias.length; i++) {
          console.log(medias[i]);
          medias[i].quality = 80;
          MediaPicker.compressImage(medias[i], (compressData) => {
            console.log('选择的图片的uri----' + compressData.uri);
            this.readBuffer(compressData.uri, medias[i].mediaType);
          }, e => {
            console.log('Can not compressImage: ' + JSON.stringify(e));
          });
        }
      }
    }, (e) => {
      console.log('Can not getMedias: ' + JSON.stringify(e));
    });
  }
  private checkAllowAdd() {
    if (this.fileObjList) {
      this.allowAdd = false;
    } else {
      this.allowAdd = true;
    }
  }

}

